<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { Plus, Check, InfoFilled, Delete } from '@element-plus/icons-vue'
import {
  avatarList,
  companion,
  companionList,
  companionDelete,
} from '../../../api/index'
import dayjs from 'dayjs'

// 弹窗显示隐藏
const dialogFormVisable = ref(false)
// 头像弹窗
const dialogImgVisable = ref(false)

// 弹窗表单引用
const formRef = ref(null)
// 弹窗表单数据
const formData = reactive({
  id: '',
  mobile: '',
  active: 1,
  age: 20,
  avatar: '',
  name: '',
  sex: '',
})

// 分页数据
const paginationData = reactive({
  pageNum: 1,
  pageSize: 10,
})

// 头像列表数据
let avatarListData =
  JSON.parse(localStorage.getItem('avatarList')) || reactive([])
// 选中的图片的下标
const selectIndex = ref(0)

// 表格数据
let TableData = reactive({
  list: [],
  total: 0,
})

// 被选择的用户
const selectUser = ref([])

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
  mobile: [
    {
      validator: validatorPhone,
      required: true,
      message: '请输入手机号',
      trigger: 'blur',
    },
  ],
  active: [{ required: true, message: '请选择头像' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
})

// 校验手机号
function validatorPhone(rule, value, callback) {
  // 不能为空
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else {
    const phoneReg =
      /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    phoneReg.test(value)
      ? callback()
      : callback(new Error('请输入正确的手机号'))
  }
}

// 获取列表数据
const getListData = () => {
  companionList(paginationData).then(({ data }) => {
    TableData.list = data.data.list
    TableData.total = data.data.total
    TableData.list.forEach((item) => {
      item.create_time = dayjs(item.create_time).format('YYYY-MM-DD')
    })
  })
}

onMounted(() => {
  // 获取图片列表(先判断有没有缓存)
  if (avatarListData.length == 0) {
    avatarList().then(({ data }) => {
      avatarListData = data.data
      // 存储到本地
      localStorage.setItem('avatarList', JSON.stringify(avatarListData))
    })
  }
  // 调用获取列表数据
  getListData()
})

// 表单提交
const confirm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 校验通过
      companion(formData).then(({ data }) => {
        if (data.code === 10000) {
          ElMessage.success('添加成功')
          // 关闭弹窗
          beforeClose()
          // 更新数据
          getListData()
        } else {
          ElMessage.error(data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 确认图片
function configrmImage() {
  formData.avatar = avatarListData[selectIndex.value].url
  // 关闭头像选择
  beforeImgClose()
}

// 全选按钮
function handleSelectionChange(val) {
  selectUser.value = val
}

// 删除用户
function deleteUser() {
  // 没有用户的情况
  if (!selectUser.value.length) {
    return ElMessage.warning('请选择要删除的用户')
  } else {
    // 删除用户
    companionDelete({ id: selectUser.value }).then(({ data }) => {
      if (data.code === 10000) {
        ElMessage.success('删除成功')
        // 重新获取数据
        getListData()
      }
    })
  }
}

// 关闭表单弹窗
function beforeClose() {
  dialogFormVisable.value = false
  // 恢复初始值
  formRef.value.resetFields()
  formData.avatar = ''
}

// 关闭头像选择弹窗
function beforeImgClose() {
  dialogImgVisable.value = false
}

// 打开编辑弹窗
function open(row) {
  dialogFormVisable.value = true
  nextTick(() => {
    if (row) {
      Object.assign(formData, row)
    }
  })
}

// 打开头像选择弹窗
function openImg() {
  dialogImgVisable.value = true
}

// 切换页数
function handleSizeChange(val) {
  paginationData.pageSize = val
  getListData()
}
// 翻页
function handleCurrentChange(val) {
  paginationData.pageNum = val
  getListData()
}
</script>

<template>
  <!-- 表单弹窗 -->
  <el-dialog
    v-model="dialogFormVisable"
    :before-close="beforeClose"
    title="添加权限"
    width="500"
  >
    <el-form
      ref="formRef"
      label-width="100px"
      label-position="left"
      :model="formData"
      :rules="rules"
    >
      <el-form-item v-show="false" prop="id">
        <el-input v-model="formData.id"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="active">
        <el-button type="primary" v-if="!formData.avatar" @click="openImg()"
          >上传头像</el-button
        >
        <el-image
          v-else
          :src="formData.avatar"
          style="width: 100px; height: 100px"
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="formData.sex" placeholder="请选择性别">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="formData.age" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="是否生效" prop="active">
        <el-radio-group v-model="formData.active">
          <el-radio :value="1">生效</el-radio>
          <el-radio :value="0">失效</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirm(formRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 头像列表的弹窗 -->
  <el-dialog
    v-model="dialogImgVisable"
    :before-close="beforeImgClose"
    title="选择图片"
    width="670"
  >
    <div class="image-list">
      <div
        v-for="(item, index) in avatarListData"
        :key="item.name"
        class="img-box"
        @click="selectIndex = index"
      >
        <div v-if="selectIndex === index" class="select">
          <el-icon color="#fff"><Check /></el-icon>
        </div>
        <el-image style="width: 148px; height: 148px" :src="item.url" />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="beforeImgClose">取消</el-button>
        <el-button type="primary" @click="configrmImage">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加按钮 -->
  <div class="btns">
    <el-button :icon="Plus" type="primary" @click="open">新增</el-button>
    <el-popconfirm
      confirm-button-text="是"
      cancel-button-text="否"
      icon="InfoFilled"
      icon-color="red"
      title="确定删除吗？"
      @confirm="deleteUser"
    >
      <template #reference>
        <el-button type="danger" :icon="Delete" size="mall">删除</el-button>
      </template>
    </el-popconfirm>
  </div>
  <PanelHead :routeData="useRoute()"></PanelHead>
  <!-- 表格 -->
  <el-table
    :data="TableData.list"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="id" />
    <el-table-column prop="name" label="名称" />
    <el-table-column label="头像">
      <template #default="scope">
        <el-image
          style="width: 50px; height: 50px"
          :src="scope.row.avatar"
        ></el-image>
      </template>
    </el-table-column>
    <el-table-column label="性别">
      <template #default="scope">
        {{ scope.row.sex == 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column prop="mobile" label="手机号" />
    <el-table-column label="状态">
      <template #default="scope">
        <el-tag class="ml-2" :type="scope.row.active ? 'success' : 'danger'">{{
          scope.row.active ? '正常' : '异常'
        }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="创建时间">
      <template #default="scope">
        <div class="flex-box">
          <el-icon><Clock></Clock></el-icon>
          <span>{{ scope.row.create_time }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="open(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="paginatin-info">
    <!-- 分页器 -->
    <el-pagination
      :page-size="paginationData.pageSize"
      :background="false"
      size="small"
      layout="total, prev, pager, next"
      :total="TableData.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </div>
</template>

<style scoped lang="less">
.btns {
  margin-bottom: 20px;
}

.image-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  row-gap: 10px;
  .img-box {
    width: 148px;
    height: 148px;
    position: relative;
    cursor: pointer;
    .select {
      width: 25px;
      height: 25px;
      position: absolute;
      top: 0;
      left: 0;
      background: green;
      z-index: 10;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.flex-box {
  display: flex;
  justify-self: center;
  align-items: center;
  span {
    margin-left: 5px;
  }
}

.paginatin-info {
  background-color: #fff;
  height: 40px;
  .el-pagination {
    height: 100%;
    box-sizing: border-box;
    padding: 0 10px;
  }
}
</style>
